import { message } from 'antd';
import api from '../../api';

export default {
  namespace: 'limitManagemen',
  state: {
    dictMap: {}, //字典
    list: undefined, //列表数据
    columns: [
      {
        title: '风险编号',
        dataIndex: 'ruleNo',
        key: 'ruleNo',
      },
      {
        title: '风险类型',
        dataIndex: 'ruleCategory',
        key: 'ruleCategory',
      },
      {
        title: '风险说明',
        dataIndex: 'ruleDesc',
        key: 'ruleDesc',
      },
      {
        title: '作用范围',
        dataIndex: 'ruleApplyObj',
        key: 'ruleApplyObj',
      },
      {
        title: '优先级',
        dataIndex: 'priority',
        key: 'priority',
      },
      {
        title: '是否启用',
        dataIndex: 'ruleState',
        key: 'ruleState',
      },
      {
        title: '比较方向',
        dataIndex: 'compareMethod',
        key: 'compareMethod',
      },
      {
        title: '生效日期',
        dataIndex: 'effectiveTime',
        key: 'effectiveTime',
      },
      {
        title: '失效日期',
        dataIndex: 'expireTime',
        key: 'expireTime',
      },
    ],
    pagination: {},
    stockList: [],
    toolInfo: [],
    stockFlag: false,
    productSelect: [],
    Factor: [],
    Condition: [],
    RootNode: [],
    productList: [], //产品下拉
    conditionOriginList: [], //证券类型 证券类别列表下拉
  },

  effects: {
    //新增里的 产品下拉
    *fetchRootNode({ payload }, { call, put }) {
      const response = yield call(api.getProducts1, payload);
      if (response && response.success) {
        //增加全部选项
        let arr = [];
        if (response.data) {
          response.data.forEach((item) => {
            arr.push({
              portfolioCode: item.value,
              portfolioName: item.title,
            });
          });
          arr.unshift({ portfolioCode: 'ALL', portfolioName: '全部' });
        }
        yield put({
          type: 'save',
          payload: {
            RootNode: arr,
          },
        });
      } else {
        const msg = response && (response.errorMsg || response.message) ? response.errorMsg : '查询失败';
        message.error(msg);
        yield put({
          type: 'save',
          payload: {
            RootNode: [],
          },
        });
      }
      return response;
    },
    // 查询限额列表
    *fetch({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.queryRules, payload);
      if (response && response.success) {
        yield put({
          type: 'save',
          payload: {
            list: response.data,
            pagination: {
              current: response.data.pageNumber,
              pageSize: response.data.pageSize,
              total: response.data.total,
            },
          },
        });
      } else {
        yield put({
          type: 'save',
          payload: {
            list: undefined,
            pagination: {},
          },
        });
        message.error('查询列表失败！');
      }
    },
    //规则选择下拉
    *getRulesData({ payload, callback }, { call, put }) {
      const response = yield call(api.limitManagemen.getRulesData, payload);

      if (response && response.code == 0) {
        callback(response.data);
      } else {
        message.error(response ? response.msg : '获取规则选择下拉列表数据失败!');
      }
    },
    //账户控制下拉
    *queryProduct({ payload }, { call, put }) {
      const response = yield call(api.getProducts, payload);
      if (response && response.success) {
        yield put({
          type: 'save',
          payload: {
            productSelect: response.data,
          },
        });
      }
      return response;
    },
    //证券范围下拉
    *queryConditionByIndexClass({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.queryConditionByIndexClass, payload);
      if (response && response.data) {
        yield put({
          type: 'save',
          payload: {
            Condition: response.data,
          },
        });
        return response;
      }
    },
    //计算因子 下拉
    *queryFactorByIndexClass({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.queryFactorByIndexClass, payload);
      if (response && response.data) {
        yield put({
          type: 'save',
          payload: {
            Factor: response.data,
          },
        });
      }
      return response;
    },
    //初始化新增页面
    *initAdd({ payload }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          data: {
            siftCondition: [],
            siftConditionRelation: ['0'],
            warnTriggerCondition: [],
            warnRuleRelation: ['0'],
            violateTriggerCondition: [],
            violateRuleRelation: ['0'],
          },
        },
      });
    },
    *createRule({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.createRule, payload);
      return response;
    },
    *modifyRule({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.modifyRule, payload);
      return response;
    },
    //查询产品
    *queryAccount({ payload }, { call }) {
      const response = yield call(api.limitManagemen.queryRootNodeAll, payload);
      return response;
    },
    //查询组合
    *getTreeAll({ payload }, { call }) {
      const response = yield call(api.limitManagemen.getTreeAll, payload);
      return response;
    },
    *deleteRule({ payload }, { call, put }) {
      const response = yield call(api.limitManagemen.deleteRule, payload);
      if (response && response.success) {
        message.success('删除成功');
        return response;
      } else {
        if (response) {
          message.error(response.message || '删除失败');
        } else {
          message.error('删除失败');
        }
        return null;
      }
    },
    *addFormula({ payload }, { select, put }) {
      const { type, formula } = payload;
      const data = yield select((state) => state.monitorSetting.data);

      let list = [];
      if ('wg' === type) {
        if (!data.violateTriggerCondition) {
          data.violateTriggerCondition = [];
        }
        list = data.violateTriggerCondition.filter((item) => item.id !== formula.id);
      } else if ('sx' === type) {
        if (!data.siftCondition) {
          data.siftCondition = [];
        }
        list = data.siftCondition.filter((item) => item.id !== formula.id);
      } else {
        if (!data.warnTriggerCondition) {
          data.warnTriggerCondition = [];
        }
        list = data.warnTriggerCondition.filter((item) => item.id !== formula.id);
      }

      list.push(formula);

      if ('wg' === type) {
        data.violateTriggerCondition = list;
      } else if ('sx' === type) {
        data.siftCondition = list;
      } else {
        data.warnTriggerCondition = list;
      }
      yield put({
        type: 'save',
        payload: {
          data,
        },
      });
    },
    *deleteFormula({ payload }, { select, put }) {
      const { id, groupId, type } = payload;
      const data = yield select((state) => state.monitorSetting.data);
      let list = [];
      if ('wg' === type) {
        list = data.violateTriggerCondition.filter((item) => item.id !== id);
        data.violateTriggerCondition = list;
      } else if ('sx' === type) {
        list = data.siftCondition.filter((item) => item.id !== id);
        data.siftCondition = list;
      } else {
        list = data.warnTriggerCondition.filter((item) => item.id !== id);
        data.warnTriggerCondition = list;
      }

      // 删除多余分组
      let flag = false;
      list.forEach((item) => {
        if (item.groupId === groupId) flag = true;
      });
      if ('wg' === type) {
        const filterList = data.violateRuleRelation.filter((item) => item !== groupId);
        if (!flag && filterList.length > 0) data.violateRuleRelation = filterList;
      } else if ('sx' === type) {
        const filterList = data.siftConditionRelation.filter((item) => item !== groupId);
        if (!flag && filterList.length > 0) data.siftConditionRelation = filterList;
      } else {
        const filterList = data.warnRuleRelation.filter((item) => item !== groupId);
        if (!flag && filterList.length > 0) data.warnRuleRelation = filterList;
      }

      yield put({
        type: 'save',
        payload: {
          data,
        },
      });
    },
    *addDiv({ payload }, { select, put }) {
      const { type } = payload;
      const data = yield select((state) => state.monitorSetting.data);

      if ('wg' === type) {
        if (!data.violateRuleRelation) {
          data.violateRuleRelation = ['0'];
        }
        const ind = data.violateRuleRelation.length - 1;
        const groupId = data.violateRuleRelation[ind];
        data.violateRuleRelation.push(`${Number(groupId) + 1}`);
      } else if ('sx' === type) {
        if (!data.siftConditionRelation) {
          data.siftConditionRelation = ['0'];
        }
        const ind = data.siftConditionRelation.length - 1;
        const groupId = data.siftConditionRelation[ind];
        data.siftConditionRelation.push(`${Number(groupId) + 1}`);
      } else {
        if (!data.warnRuleRelation) {
          data.warnRuleRelation = ['0'];
        }
        const ind = data.warnRuleRelation.length - 1;
        const groupId = data.warnRuleRelation[ind];
        data.warnRuleRelation.push(`${Number(groupId) + 1}`);
      }

      yield put({
        type: 'save',
        payload: {
          data,
        },
      });
    },
    //查询模板列表
    *queryTemplateList({ payload, callback }, { call, put }) {
      const res = yield call(api.limitManagemen.queryTemplateList, payload);
      if (res && res.code == 0) {
        callback(res.data ? res.data.dataSource : []);
      } else {
        callback([]);
        message.error(res && res.msg ? res.msg || '查询模板列表失败' : '查询模板列表失败');
      }
    },
    //删除模板
    *deleteTemplate({ payload, callback }, { call, put }) {
      const res = yield call(api.limitManagemen.deleteTemplate, payload);
      if (res && res.code == 0) {
        callback();
        message.success('删除模板成功');
      } else {
        message.error(res && res.msg ? res.msg || '删除模板失败' : '删除模板失败');
      }
    },
    //另存为
    *addTemplate({ payload, callback }, { call, put }) {
      const res = yield call(api.limitManagemen.addTemplate, payload);
      if (res && res.code == 0) {
        callback();
        message.success('新增模板成功');
      } else {
        message.error(res && res.msg ? res.msg || '新增模板失败' : '新增模板失败');
      }
    },
    //保存编辑
    *editTemplate({ payload, callback }, { call, put }) {
      const res = yield call(api.limitManagemen.editTemplate, payload);
      if (res && res.code == 0) {
        callback();
        message.success('保存模板成功');
      } else {
        message.error(res && res.msg ? res.msg || '保存模板失败' : '保存模板');
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
